package com.toman.ui.work.workshop;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.toman.Enum.NetworkEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.ReceiveSendworkOrderDto;
import com.toman.R;
import com.toman.Util.DefaultAcitonCallback;
import com.toman.Util.DialogUtils;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.camera.Camera;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.ClearEditText;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SubmitMoreActivity extends ToolBarActivity {
    Camera camera;
    @BindView(R.id.tv_sendwork_code)
    TextView tvSendworkCode;
    @BindView(R.id.rl_order_code)
    RelativeLayout rlOrderCode;
    @BindView(R.id.tv_product_name)
    TextView tvProductName;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_beltline_child)
    TextView tvBeltlineChild;
    @BindView(R.id.et_completed_count)
    ClearEditText etCompletedCount;
    @BindView(R.id.et_qualified_count)
    ClearEditText etQualifiedCount;
    @BindView(R.id.et_waste_count)
    ClearEditText etWasteCount;
    @BindView(R.id.et_scrapped_count)
    ClearEditText etScrappedCount;
    @BindView(R.id.et_remake_count)
    ClearEditText etRemakeCount;
    @BindView(R.id.et_reuse_count)
    ClearEditText etReuseCount;
    Dialog dialog;
    ReceiveSendworkOrderDto bean;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_order_remark_name)
    TextView tvOrderRemarkName;
    @BindView(R.id.et_order_remark)
    EditText etOrderRemark;
    @BindView(R.id.tv_shift)
    TextView tvShift;
    @BindView(R.id.rl_shift)
    RelativeLayout rlShift;
    @BindView(R.id.tv_operator)
    TextView tvOperator;
    @BindView(R.id.rl_operator)
    RelativeLayout rlOperator;
    String opUserId="";
    String shiftId="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_more);
        ButterKnife.bind(this);
        initToolBar("量产报工");
        initHandler();
        initIntent();
        initView();
    }

    private void initView() {
        camera = ViewUtil.createPhoto("请提供相关截图或照片", camera, this, ll);
        opUserId=(String) SPUtils.get(this, "userid", "");
        String[] item = new String[]{bean.getSendworkorderEntity().getSendworkCode() + "", bean.getProductEntity().getProductName(),
                bean.getOperationorderEntity().getOrderName(), bean.getBeltlineEntity().getBeltlineName(),(String) SPUtils.get(this, "username", "")};//直接初始化
        ViewUtil.setText(item, tvSendworkCode, tvProductName, tvOrderName, tvBeltlineChild,tvOperator);
        ViewUtil.click(tvShift,tvOperator);

    }

    private void initIntent() {
        bean = (ReceiveSendworkOrderDto) getIntent().getSerializableExtra("bean");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_finish, menu);

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_finish:
                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }

    public void add() {
        String[] item = new String[]{"操作工","完工数量", "合格数量", "报废数量", "料废数量", "返工数量", "回用数量"};//直接初始化

        if (ViewUtil.isNull(this, item, tvOperator,etCompletedCount, etQualifiedCount, etScrappedCount, etWasteCount, etRemakeCount, etReuseCount)
                ) {
            return;
        }
      String[] item2 = new String[]{"完工数量", "合格数量"};//直接初始化
        if (ViewUtil.compareString(this, item2, etCompletedCount, etQualifiedCount)
                ) {
            return;
        }

        List<String> list = camera.getCompressUrl();
        Map<String, String> map = new HashMap<String, String>();
        map.put("mappingId", bean.getMappingId() + "");
        map.put("completedCount", etCompletedCount.getText().toString());
        map.put("qualifiedCount", etQualifiedCount.getText().toString());
        map.put("scrappedCount", etScrappedCount.getText().toString());
        map.put("wasteCount", etWasteCount.getText().toString());
        map.put("remakeCount", etRemakeCount.getText().toString());
        map.put("reuseCount", etReuseCount.getText().toString());
        map.put("batchReportAddDesc", etOrderRemark.getText().toString());
        map.put("shiftId", shiftId);
        map.put("opUserId", opUserId);
        map.put("token", token);
        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");
        upload((HashMap<String, String>) map, list);
    }

    private void upload(HashMap<String, String> map, List<String> paths) {
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);

//遍历map中所有参数到builder
        for (String key : map.keySet()) {
            mbody.addFormDataPart(key, map.get(key));
        }


        for (String path : paths) {
            File file = new File(path);
            if (file.exists()) {
                mbody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
            // builder.addFormDataPart("file[]", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
        }


        //构建请求体
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")
                .url(NewBaseUrl.workshop_submit_benchreport)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                dialog.dismiss();

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                Log.i(getClass().toString() + ":", result);
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");
                ViewUtil.lagout(code, getApplicationContext());
                if (code == 0) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
            }
        });


    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        dialog.dismiss();
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);
                        finish();
                        break;
                    case 2:
                        dialog.dismiss();
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);

                        break;
                    default:
                        break;
                }
            }
        };
    }

    @OnClick({R.id.tv_shift, R.id.tv_operator})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_shift:
                Map<String, String> map = new HashMap<>();
                map.put("departmentId", departmentId);
                DialogUtils.showDialog(this, NetworkEnum.SHIFT, mCompanyId,map, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        tvShift.setText(bean1.getName());
                        shiftId=bean1.getID();
                        dialog.dismiss();
                    }
                });
                break;
            case R.id.tv_operator:
                DialogUtils.showDialog(this, NetworkEnum.OPERATOR, mCompanyId,new HashMap<String, String>(){{put("beltlineId",bean.getBeltlineEntity().getId()+"");}}, new DefaultAcitonCallback() {
                    @Override
                    public void run(ItemListBean bean1, Dialog dialog) {
                        tvOperator.setText(bean1.getName());
                        opUserId=bean1.getID();
                        dialog.dismiss();
                    }
                });
                break;
        }
    }
}
